package com.rongke.damo.medicalrecord.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.rongke.biz.service.MedicalRecordManager;
import com.rongke.biz.service.UserManager;
import com.rongke.commons.JsonResp;
import com.rongke.model.Chemotherapy;
import com.rongke.model.ChemotherapyMedicine;
import com.rongke.model.InspectionRecord;
import com.rongke.model.MedicalRecords;
import com.rongke.model.User;
import com.rongke.service.ChemotherapyMedicineService;
import com.rongke.service.ChemotherapyService;

import org.apache.commons.collections.CollectionUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import jodd.util.StringUtil;

/**
 * @ChemotherapyController
 * @化疗方案Controller
 * @version : Ver 1.0
 */
@RestController
@RequestMapping(value = "/api/damo/chemotherapy")
@Transactional
public class DamoChemotherapyController {
    private static final Logger         LOGGER = Logger.getLogger(DamoChemotherapyController.class);

    @Autowired
    private ChemotherapyService         chemotherapyService;

    @Autowired
    private ChemotherapyMedicineService chemotherapyMedicineService;

    @Autowired
    private UserManager                 userManager;

    @Autowired
    private MedicalRecordManager        medicalRecordManager;

    /**
     * @添加化疗方案
     * @param chemotherapy
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public JsonResp addChemotherapy(@RequestBody Map<String, String> jsonMap) {
        LOGGER.debug("addChemotherapy");

        try {
            String mobileNo = jsonMap.get("phone");
            if (StringUtil.isEmpty(mobileNo)) {
                return JsonResp.fa(null);
            }

            User user = userManager.selectOrAddUser(mobileNo);
            if (null == user) {
                return JsonResp.fa(null);
            }
            String userId = user.getUserId();

            MedicalRecords mrInfo = medicalRecordManager.selectOrAddMrByUserId(userId);
            if (null == mrInfo) {
                return JsonResp.fa(null);
            }
            long mrId = mrInfo.getId();

            Chemotherapy chemotherapyInfo = new Chemotherapy();
            chemotherapyInfo.setMedicalRecordId(mrId);
            chemotherapyInfo.setUserId(userId);
            chemotherapyInfo.setPicContent(jsonMap.get("picContent"));
            chemotherapyInfo.setRemark(jsonMap.get("remark"));
            chemotherapyInfo.setStartDate(jsonMap.get("startDate"));
            chemotherapyInfo.setEndDate(jsonMap.get("endDate"));
            chemotherapyInfo.setTagInfo(jsonMap.get("tagInfo"));
            chemotherapyService.insert(chemotherapyInfo);

            String medicineListStr = jsonMap.get("medicineList");
            List<ChemotherapyMedicine> medicineList = JSONObject.parseArray(medicineListStr,
                ChemotherapyMedicine.class);
            if (CollectionUtils.isNotEmpty(medicineList)) {
                for (ChemotherapyMedicine medicine : medicineList) {
                    medicine.setChemotherapyId(chemotherapyInfo.getId());
                    chemotherapyMedicineService.insert(medicine);
                }
            }

            JSONObject json = new JSONObject();
            json.put("id", chemotherapyInfo.getId());
            return JsonResp.ok(json);
        } catch (Exception e) {
            LOGGER.error("addChemotherapy failed", e);
            // 手动回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return JsonResp.fa(null);
        }
    }

    /**
     * @修改化疗方案
     * @param chemotherapy
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public JsonResp updateChemotherapy(@RequestBody Chemotherapy chemotherapy) {
        LOGGER.debug("updateChemotherapy");

        try {
            Chemotherapy cheInfo = new Chemotherapy();
            cheInfo.setId(chemotherapy.getId());
            cheInfo.setGmtModified(new Date());
            cheInfo.setPicContent(chemotherapy.getPicContent());
            cheInfo.setRemark(chemotherapy.getRemark());
            cheInfo.setStartDate(chemotherapy.getStartDate());
            cheInfo.setEndDate(chemotherapy.getEndDate());
            cheInfo.setTagInfo(chemotherapy.getTagInfo());

            chemotherapyService.updateById(cheInfo);

            // 删除旧的用药信息
            Map<String, Object> param = new HashMap<String, Object>();
            param.put("chemotherapy_id", chemotherapy.getId());
            chemotherapyMedicineService.deleteByMap(param);
            // 重新插入
            List<ChemotherapyMedicine> medicineList = chemotherapy.getMedicineList();
            if (CollectionUtils.isNotEmpty(medicineList)) {
                for (ChemotherapyMedicine medicine : medicineList) {
                    medicine.setChemotherapyId(chemotherapy.getId());
                    chemotherapyMedicineService.insert(medicine);
                }
            }

            JSONObject json = new JSONObject();
            json.put("id", chemotherapy.getId());
            return JsonResp.ok(json);
        } catch (Exception e) {
            LOGGER.error("updateChemotherapy failed", e);
            // 手动回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return JsonResp.fa(null);
        }
    }

    @RequestMapping(value = "/del", method = RequestMethod.POST)
    public JsonResp delChemotherapyById(long id) {
        if (LOGGER.isInfoEnabled()) {
            LOGGER.info("delChemotherapyById, id=" + id);
        }

        try {
            chemotherapyService.deleteById(id);

            Map<String, Object> param = new HashMap<String, Object>();
            param.put("chemotherapy_id", id);
            chemotherapyMedicineService.deleteByMap(param);

            JSONObject json = new JSONObject();
            json.put("id", id);
            return JsonResp.ok(json);
        } catch (Exception e) {
            LOGGER.error("delChemotherapyById failed, id=" + id, e);
            // 手动回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return JsonResp.fa(null);
        }
    }

    /**
     * @根据id查找化疗方案
     * @param id
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/selectOne", method = RequestMethod.GET)
    public JsonResp selectChemotherapy(Long id) {
        LOGGER.debug("selectChemotherapy");
        try {
            Chemotherapy chemotherapy = chemotherapyService.selectById(id);
            if (null == chemotherapy) {
                return JsonResp.ok();
            }

            Map<String, Object> param = new HashMap<String, Object>();
            param.put("chemotherapy_id", id);
            List<ChemotherapyMedicine> medicineList = chemotherapyMedicineService
                .selectByMap(param);
            chemotherapy.setMedicineList(medicineList);

            return JsonResp.ok(chemotherapy);
        } catch (Exception e) {
            LOGGER.error("selectChemotherapy failed", e);
            return JsonResp.fa(null);
        }
    }

    @RequestMapping(value = "/selectAllByPhone", method = RequestMethod.GET)
    public JsonResp selectList(String userId) {
        if (LOGGER.isInfoEnabled()) {
            LOGGER.info("selectList, userId=" + userId);
        }

        try {
            MedicalRecords mr = medicalRecordManager.selectByUserId(userId);
            if (null == mr) {
                return JsonResp.ok();
            }

            long mrId = mr.getId();

            EntityWrapper<Chemotherapy> ew = new EntityWrapper<Chemotherapy>();
            ew.eq("medical_record_id", mrId);
            ew.orderBy("start_date");
            List<Chemotherapy> result = chemotherapyService.selectList(ew);

            //还需要具体的药品信息
            if (CollectionUtils.isNotEmpty(result)) {
                for (Chemotherapy chemotherapy : result) {
                    List<ChemotherapyMedicine> medicineList = chemotherapyMedicineService
                        .selectByChemoId(chemotherapy.getId());
                    chemotherapy.setMedicineList(medicineList);
                }
            }

            // 查询列表时，不需要查询具体的用药情况
            return JsonResp.ok(result);
        } catch (Exception e) {
            LOGGER.error("selectList failed, userId=" + userId, e);
            return JsonResp.fa(null);
        }
    }
}
